'use strict';
/**
 * ip middleware
 */
export default class extends think.middleware.base {
    /**
     * run
     * @return {} []
     */
    run() {
        let ipCfg = think.config('ip');
        if (!ipCfg) {
            return;
        }

        let ipWhite = ipCfg.white;
        let ipBlack = ipCfg.black;

        if(!ipWhite && !ipBlack){
            return;
        }

        let ip = this.http.ip();
        let ips = ip.split('.');

        if (ipWhite) {
            let checked = this.checkIp(ip, ipWhite);
            if (!checked) {
                return this.showError();
            }
            return;
        }

        if (ipBlack) {
            let checked = this.checkIp(ip, ipBlack);
            if (checked) {
                return this.showError();
            }
            return;
        }

        return;
    }

    checkIp(ip, ipList) {
        let ips = ip.split('.');
        let flag = ipList.some(_ip => {
            if (think.isIP(_ip)) {
                let _ips = _ip.split('.');
                return _ips.every((num, i) => {
                    if(num==='*' || num==ips[i]){
                        return true;
                    }
                });
            }
        });
        return flag;
    }

    showError() {
        this.http.error = new Error('ip is not allowed!');
        return think.statusAction(403, this.http);
    }

}